#!/usr/bin/python 

"""
Copyright 2008 Israel Garcia

This file is part of Audlib.
Audlib is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.

Audlib is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Audlib.  If not, see <http://www.gnu.org/licenses/>.
"""

import gobject
from gst.extend.discoverer import Discoverer
from urllib import unquote, quote

gobject.threads_init()

class TagsDiscoverer():
    def __init__(self, uri_list):
        #self.file_list = self._convert_to_filelist(uri_list)
        self.TAGS = ('artist', 'album', 'title', 'duration', 'track-number', 'comment')
        self.uri_list = [unquote(i)[7:] for i in uri_list]
        self.results = []
        self.mainloop = gobject.MainLoop()
        gobject.idle_add(self._analize_one)
        self.mainloop.run()

    def get_tags(self):
        """
        Dumb method, because __init__ must not return.
        """
        return self.results

    def _parse_tags(self, tags_dic):
        ls = []
        for tag in self.TAGS:
            try: 
                ls.append(tags_dic[tag])
            except:
                ls.append('')
        return ls
        
    def _analize_one(self):
        if not len(self.uri_list):
            gobject.idle_add(self.mainloop.quit)
            return False
        f = self.uri_list.pop(0)
        d = Discoverer(f)
        d.connect('discovered', self._discovered, f)
        d.discover()
        return False
    
    def _discovered(self, d, is_media, f):
        if not is_media:
            print "%s is not a media file" % f
        else:
            tags =  d.tags
            tags['duration'] = str(d.audiolength)
            ans = self._parse_tags(tags)
            ans.insert(0, 'file://' + quote(f))
            myans = tuple(ans)
            self.results.append(myans)
        gobject.idle_add(self._analize_one)
    
if __name__ == '__main__':
    t = TagsDiscoverer(["file:///media/hda2/linux/musica/Tobe/Electronic/Melotron%20-%20Br%C3%BCder%20E.P/melotron%20-%20Br%C3%BCder%20E.P.%20-%2005%20-%20Wohin%20%28monoton%29-1.mp3"]).get_tags()
    print t
